package com.sdgakj.service.msg;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Message;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.repository.MessageDao;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.MsgSearchFilter;
import com.sdgakj.utils.MsgSpecifications;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Transactional
public class MessageService {
	
	@Autowired
	private MessageDao messageDao;
	
	@Autowired
	private UserService userService;
	
	public List<Message> getMessageByName(String name) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (StringUtils.isNotBlank(name)) {
			filters.put("msg", new SearchFilter("name", Operator.LIKE, name));
		}
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
		return messageDao.findAll(spec);
	}
	
	public List<Long> getMessageByType(long uid, String type, String device, String deltag){
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, MsgSearchFilter> filters = MsgSearchFilter.parse(searchParams);
		filters.put("deltag", new MsgSearchFilter("deltag", MsgSearchFilter.Operator.EQ, deltag));
		filters.put("type", new MsgSearchFilter("type", MsgSearchFilter.Operator.EQ, type));
		if(!"4".equals(device)) {
			filters.put("device", new MsgSearchFilter("device", MsgSearchFilter.Operator.IN, device + "," + 4));
		}
		if(uid != 0l) {
			User c = userService.getUserById(uid);
			filters.put("createDate", new MsgSearchFilter("createDate", MsgSearchFilter.Operator.GTE, c.getRegisterDate()));
		}
		Specification<Message> spec = MsgSpecifications.bySearchFilter(filters.values(), Message.class);
		List<Message> list =  messageDao.findAll(spec);
		List<Long> ids=new ArrayList<Long>();
		if(!list.isEmpty()){
			for(Message tm:list){
				ids.add(tm.getId());
			}
		}
		return ids;
	}

	public Message getMessage(Long id) {
		return messageDao.findOne(id);
	}
	
	public List<Message> getMessageList() {
		return (List<Message>) messageDao.findAll();
	}
	
	public Message saveMessage(Message entity) {
		return messageDao.save(entity);
	}
	
	public void updateMessage(Message entity) {
		messageDao.save(entity);
	}
	
	public void deleteMessage(Long id) {
		Message tempMessage = this.getMessage(id);
		tempMessage.setDeltag(EnumIsDelete.DELETED.getCode());
		this.saveMessage(tempMessage);
		
	}
	
	public List<Message> getMessageAllByTag(String deltag) {
		return messageDao.findByTag(deltag);
	}
	
	public Page<Message> getMessage(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortName,
											  String sortType) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, Direction.DESC, "createdate");

        // Specification<Truck> spec = buildSpecification(searchParams);
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
		
	}

	/**
	 * 创建排序.
	 */
	private Sort buildSortRequest(String sortName,String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}else if("desc".equals(sortType)){
			sort = new Sort(Direction.DESC, sortName);
		}else{
			sort = new Sort(Direction.ASC, sortName);
		}
		return sort;
	}
	
	/**
	 * 创建分页请求.
	 */
	public PageRequest buildPageRequest(int pageNumber, int pagzSize,  String sortName,String sortType) {
		Sort sort = buildSortRequest(sortName, sortType);
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	public List<Message> getMessageAllByTag(String deltag, String sortName, String sortType) {
		Map<String, SearchFilter> filters = Maps.newHashMap();
		if (StringUtils.isNotBlank(deltag)) {
			filters.put("deltag", new SearchFilter("deltag", Operator.EQ, deltag));
		}
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
		Sort sort = buildSortRequest(sortName,sortType);
		return messageDao.findAll(spec, sort);
	}
	
	
	public Message productMessage(String type, String mode, String device, String[] ddlIds , String msg, String tag) {
		Message tm = new Message();
		tm.setType(type);
		tm.setMsg(msg);
		tm.setMode(mode);
		tm.setDevice(device);
		tm.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		tm.setCreatedate(new Date());
		return this.saveMessage(tm);
	}
	
	public Message productMessage(String type, String mode, String device, String msg, String tag, Long uid) {
		Message tm = new Message();
		tm.setType(type);
		tm.setMsg(msg);
		tm.setMode(mode);
		tm.setDevice(device);
		tm.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		tm.setCreatedate(new Date());
		tm.setUserId(uid);
		return this.saveMessage(tm);
	}
	
	public Message productMessage(String type, Integer category, String link, String mode, String device, String msg, String createdate, String tag, Long uid, String title, Long userid) {
		Message tm = new Message();
		tm.setType(type);
		tm.setMsg(msg);
		tm.setMode(mode);
		tm.setLink(link);
		tm.setDevice(device);
		tm.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		Date theDate = null;
	    if(StringUtils.isNoneBlank(createdate)) {
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	try {
				theDate = sdf.parse(createdate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
		if(theDate != null) {
			tm.setCreatedate(theDate);
		} else {
			tm.setCreatedate(new Date());
		}
		if(uid!=null && uid>0){
		    tm.setUserId(uid);
		}
		tm.setTitle(title);
		if(userid!=null && userid>0){
			tm.setUserId(userid);
		}
		return this.saveMessage(tm);
	}
	
	
	public Message productnewMessage(String type, Integer category, String link, String mode, String device, String msg, String createdate, String tag, Long uid, String title, Long userid) {
		Message tm = new Message();
		tm.setType(type);
		tm.setMsg(msg);
		tm.setMode(mode);
		tm.setLink(link);
		tm.setDevice(device);
		tm.setDeltag(EnumIsDelete.DELETED.getCode());
		Date theDate = null;
	    if(StringUtils.isNoneBlank(createdate)) {
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	try {
				theDate = sdf.parse(createdate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
		if(theDate != null) {
			tm.setCreatedate(theDate);
		} else {
			tm.setCreatedate(new Date());
		}
		tm.setTitle(title);
		if(userid!=null && userid>0){
			tm.setUserId(userid);
		}
		return this.saveMessage(tm);
	}

	public Message getMessageByCustomer(Long id, String code) {
		Message message=null;
		Long ids=messageDao.getMessageByCustomer(id,code);
		if(ids!=null){
			message=messageDao.findOne(ids);
		};
		return message;
	}
/**
 * 列表
 * @param pageNumber 页号
 * @param pageSize   每页大小
 * @param sortType   排序字段
 * @param model
 * @param request
 * @return
 */

	/*public static List<Message> getMessageByType(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) {
		try {
			PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
			Sort sort = buildSortRequest(sortName, sortType);
			Specification<Message> spec = buildSpecification(searchParams);
			Page<Message> Messages = MessageDao.findAll(spec, pageRequest);
		} catch (Exception e) {
			return Messages;
		}



}*/



}
